#include "fw_hal.h"

#define TEMP_ADC_CHANNEL  0x04
#define PHOTO_ADC_CHANNEL 0x05

// Temp Pin: P5.4
#define TEMP_PIN          GPIO_Pin_4
// Photoresistor Pin: P5.5
#define PHOTO_PIN         GPIO_Pin_5

uint8_t  adc_channel;
uint16_t temp_adc = 0, photo_adc = 0;

INTERRUPT(ADC_Routine, EXTI_VectADC) {
  // 清楚 ADC 中断信号
  ADC_ClearInterrupt();

  if (adc_channel == TEMP_ADC_CHANNEL) {
    temp_adc = ADC_RESL;
    temp_adc |= (ADC_RES & 0x0f) << 8;
    adc_channel = PHOTO_ADC_CHANNEL;
  } else {
    photo_adc = ADC_RESL;
    photo_adc |= (ADC_RES & 0x0f) << 8;
    adc_channel = TEMP_ADC_CHANNEL;
  }
  // 切换 ADC 通道
  ADC_SetChannel(adc_channel);
  // 开始 ADC 进程
  ADC_Start();
}

int main (void) {
  UART1_Config8bitUart(UART1_BaudSource_Timer1, HAL_State_ON, 115200);;
  GPIO_P5_SetMode(TEMP_PIN, GPIO_Mode_Input_HIP);
  GPIO_P5_SetMode(PHOTO_PIN, GPIO_Mode_Input_HIP);;
  // 从温度通道开始读取信息
  adc_channel = TEMP_ADC_CHANNEL;
  ADC_SetChannel(adc_channel);
  // ADC Clock = SYSCLK / 2 / (1 + 15)
  ADC_SetClockPrescaler(0x0f);
  // 10-bit ADC: high 2-bit in ADC_RES, low 8-bit in ADC_RESL
  ADC_SetResultAlignmentRight();
  
  // 开启中断
  EXTI_Global_SetIntState(HAL_State_ON);
  EXTI_ADC_SetIntState(HAL_State_ON);
  
  // 启动 ADC 
  ADC_SetPowerState(HAL_State_ON);
  ADC_Start();;

  while (1) {
    UART1_TxString("Temp ADC: 0x");
    UART1_TxHex(temp_adc >> 8);
    UART1_TxHex(temp_adc & 0xff);
    UART1_TxString(" Photo ADC: 0x");
    UART1_TxHex(photo_adc >> 8);
    UART1_TxHex(photo_adc & 0xff);
    UART1_TxString("\r\n");
    SYS_Delay(1000);
  }
}
